package xyz.sicau.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Order(-1) // -1表示优先级最高，值越大，优先级越低，也可以实现Ordered接口
// @Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // MultiValueMap 运行一键多值
        MultiValueMap<String, String> params = request.getQueryParams();

        String auth = params.getFirst("auth");

        if ("admin".equals(auth))
            return chain.filter(exchange); // 放行，就是调用下一个filter
        // 最好返回一个状态码，让前端知道为什么不放行
        // exchange.getResponse().setRawStatusCode(401); // 和下面操作一样
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
